package cn.itsource.template;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.itsource.exception.GlobalException;
import cn.itsource.pojo.properties.OssProperties;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 📖：beishan
 * 🗓️：2024/4/5 19:06
 * =====================
 */
@Slf4j
public class OssTemplate {

    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    /**
     *  将文件上传到阿里云
     * @param file 前端传入的文件
     * @param dir 保存阿里云的目录
     * @return
     */
    public String upload(MultipartFile file, String dir) {
        String endpoint = ossProperties.getEndpoint();
        String accessKeyId = ossProperties.getAccesskeyid();
        String accessKeySecret = ossProperties.getAccesskeysecret();
        String bucketName = ossProperties.getBucketname();
        String resultUrl = ossProperties.getResultUrl();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String extName = FileNameUtil.extName(file.getOriginalFilename());
        String uuid = IdUtil.fastSimpleUUID();
        String objectName = dir + "/" + uuid + "." +extName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //https://fccar-beishan.oss-cn-chengdu.aliyuncs.com/auth/0e112998e2384bca87af19a2cb542fde.jpg

        String substring = endpoint.substring(endpoint.lastIndexOf("/") + 1);
        String url = String.format(resultUrl, bucketName, substring, objectName);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info(String.valueOf(result));

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }

    public String download(String dir,String url){
        String accessKeyId = ossProperties.getAccesskeyid();
        String accessKeySecret = ossProperties.getAccesskeysecret();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossProperties.getEndpoint();
        //从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ossProperties.getBucketname();
        // 填写不包含Bucket名称在内的Object完整路径，例如testfolder/exampleobject.txt。
        String substring = url.substring(url.lastIndexOf("/") + 1);
        String objectName = dir + "/" + substring;
        // 填写Object下载到本地的完整路径。
        String pathName = "D:\\excel\\"+objectName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
            // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return pathName;
    }
}

